<!--
 * @Descripttion: 
 * @Author: yuxi
 * @Date: 2022-09-15 14:58:04
 * @LastEditors: yuxi
 * @LastEditTime: 2023-03-12 20:58:37
-->
<template>
  <div class="map-container">
    <MiningMap
      :center="center"
      :zoom="zoom"
      :useContextMenu="true"
      :customContextMenus="customContextMenus"
      @selected="handleSelected"
    >
      <MiningTiandituLayer
        layerName="基础底图"
        :ak="key"
        @ready="ready"
        layerType="img_w"
      ></MiningTiandituLayer>
      <MiningVectorLayer
        :customContextMenus="customContextMenus"
        :featureStyle="style"
        v-for="(layer, li) in layers"
        :key="layer.layerId"
        :layerName="layer.layerName"
        :layerId="layer.layerId"
        :properties="layer"
        @ready="reloadLayerControl"
      >
        <MiningLineString
          v-for="feature in groupFeatures[layer.layerId]"
          :key="feature.get('properties').id"
          :feature="feature"
        >
        </MiningLineString>
        <MiningPoint
          v-for="feature in groupPoints[layer.layerId]"
          :key="feature.get('properties').id"
          :feature="feature"
        >
        </MiningPoint>
      </MiningVectorLayer>

      <MiningLayerControl ref="layerControl">
        <template #layer="{ layer, layer_index, properties }">
          <MiningLayerControlItem :layer="layer">
            <template #addon>
              <div>
                <!-- <i class="el-icon-edit"></i> -->
                <!-- <i v-if="layer_index > 0 && !properties.isLock" class="el-icon-lock" @click="startEdit(layer)" style="margin-right: 5px;"></i>
                <i v-if="layer_index > 0 && properties.isLock" class="el-icon-unlock" @click="endEdit(layer)" style="margin-right: 5px;"></i>
                <i v-if="layer_index > 0" class="el-icon-delete" @click="removeLayer(layer)"></i> -->
              </div>
            </template>
          </MiningLayerControlItem>
        </template>
        <template #extend>
          <div class="add-btn">
            <!-- <el-button size="small" @click="handleAddLayer">添加图层</el-button>  -->
          </div>
        </template>
      </MiningLayerControl>
    </MiningMap>
  </div>
</template>

<script>
import MiningMap from 'mining-map/Map'
import MiningTiandituLayer from 'mining-map/Layers/TiandituLayer'
import { TiandituKey } from '@/config/config.js';
import { Style, Stroke as StrokeStyle, Fill as FillStyle, Icon } from 'ol/style';
 
import MiningLayerControl from 'mining-map/Control/LayerControl';
import MiningLayerControlItem from 'mining-map/Control/LayerControlItem';
import MiningVectorLayer from 'mining-map/Layers/VectorLayer'
import MiningPoint from 'mining-map/Features/Point';
import MiningLineString from 'mining-map/Features/LineString';
import marker from '@/assets/images/light.png'
import { findAndCountAll } from '@/apis/attr'

import { findAndCountAll as findAllGeos, splitLine } from '@/apis/geo'

import GeoJSON from 'ol/format/GeoJSON';
import Feature from 'ol/Feature'; 
 
export default {
  name: 'PointManager',
  title: '灯塔图层',
  parentTitle: '业务组件',
  components: {
    MiningMap,
    MiningTiandituLayer,
    MiningLayerControl,
    MiningLayerControlItem,
    MiningVectorLayer,
    MiningLineString,
    MiningPoint
  },
  data () {
    const style = new Style({
      stroke: new StrokeStyle({
        color: 'blue',
        lineDash: [4],
        width: 3,
      }),
      fill: new FillStyle({
        color: 'rgba(0, 0, 255, 0.1)',
      }),
      image: new Icon({
        anchor: [0.5, 1],
        anchorXUnits: 'fraction',
        anchorYUnits: 'fraction',
        // size: [5, 15],
        // size: new olSize(15, 15),
        scale: 0.2,
        src: marker,
      })
    })
    return {
      center: [116.43396401346438, 39.926523711148874],
      zoom: 17,
      key: TiandituKey,
      draw: null,
      snap: null,
      select: null,
      layers: [],
      style,
      map: null,
      features: [],
      selectFeature: null,
      points: [],
      activeFeature: null
    }
  },
  created () {
    this.fetchLayers()
  },
  computed: { 
    groupFeatures () {
      let groups = {}
      this.features.map(f => {
        let properties = f.get('properties')
        groups[properties.layer_id] = groups[properties.layer_id] || []
        groups[properties.layer_id].push(f)
      })

      return groups
    },
    groupPoints () {
      let groups = {}
      this.points.map(f => {
        let properties = f.get('properties')
        groups[properties.layer_id] = groups[properties.layer_id] || []
        groups[properties.layer_id].push(f)
      })
      return groups
    },
    // 自定义菜单
    customContextMenus () {
      return this.activeFeature? [{
        name: '分割选中折线',
        handler: this.handleSplit
      }]: []
    }
  },
  watch: {
    
  },
  methods: {
    ready ({ map }) {
      this.map = map 
    },
    fetchLayers () {
      findAndCountAll({
        table: 'layer_info',
        page: 1,
        pageSize: 100
      }).then(res => {
        if (res.code === 0) {
          this.layers = res.data.rows.filter(r => {
            return !r.geom
          })
            .map(r => {
              return {
                layerId: r.id,
                layerName: r.name,
                type: 'vectorLayer',
                isLock: r.isLock
              }
            })
          this.findAllGeos()
          this.$nextTick(() => {
            this.reloadLayerControl()
          })
        }
      })
    },
    findAllGeos () {
      findAllGeos({
        table: 'line',
        page: 1,
        pageSize: 100
      }).then(res => {
        if (res.code === 0) {
          this.features = res.data.rows.map(r => {
            return new Feature({
              type: 'LineString',
              geometry: new GeoJSON().readGeometry(r.geom),
              name: r.id,
              properties: {
                id: r.id,
                layer_id: r.layer_id
              }
            })
          }) 
          this.findAllPoints()
        }
      })

    },
    findAllPoints () {
      findAllGeos({
        table: 'point',
        page: 1,
        pageSize: 1000
      }).then(res => {
        if (res.code === 0) {
          this.points = res.data.rows.map(r => {
            return new Feature({
              type: 'Point',
              geometry: new GeoJSON().readGeometry(r.geom),
              name: r.id,
              properties: {
                id: r.id,
                layer_id: r.layer_id,
                line_id: r.line_id
              }
            })
          })

        }
      })
    },   
    reloadLayerControl () {
      this.$refs.layerControl.load()
    },
    // 获取激活要素
    handleSelected (active, unActive) {
      if (active && active.feature.get('type') === 'LineString') {
        this.activeFeature = active
        // 高亮
        this.activeFeature.feature.setStyle(new Style({
          stroke: new StrokeStyle({
            color: 'red',
            width: 2,
          }),
        }))
      } else if (unActive) {
        unActive.feature.setStyle(this.style)
        // 恢复样式
        this.activeFeature = null
      }
    },
    // 生成灯塔数据
    handleSplit (evt) {
      if (evt.selected && evt.selected.length > 0) {
        let lineId = evt.selected[0].feature.get('properties').id
        splitLine({
          table: 'line',
          id: lineId,
          params: {
            total: 4
          }
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('生成成功')
            this.points = this.points.filter(p => {
              console.log(p)
              return p.get('properties').line_id !== lineId
            }).concat(res.data.map(r => {
              return new Feature({
                type: 'Point',
                geometry: new GeoJSON().readGeometry(r.geom),
                name: r.id,
                properties: {
                  id: r.id,
                  layer_id: r.layer_id,
                  line_id: r.line_id
                }
              })
            }))
          }
        })
      }
    }

  }

}
</script>

<style lang="less">
body,
html {
  padding: 0;
  margin: 0;
}

.map-container {
  width: 100%;
  height: 100vh;
  text-align: left;

  .add-btn {
    padding: 20px;
    text-align: center;
  }
}
</style>